package com.iseastar.login;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.WebViewActivity;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;
import com.shouhuobao.take.MainActivity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import droid.frame.utils.lang.Str;

/**
 * 登陆选择（裹将or驿站）
 *
 * @author HuXinDan<br>
 * 2016-11-22上午11:03:48
 */
public class LoginChooseActivity extends BaseActivity2 implements OnClickListener {

    private BroadcastReceiver smsReceiver;
    private IntentFilter smsFilter;

    private EditText mMobileEdit, mCodeEdit;// 手机号验证码
    private TextView mGetCodeTextView; // 获取验证码
    private TextView mSubmitTV;// 登录
    private CheckBox mCheckBox;// 是否同意服务条款
    private String loginPhone;// 正在获取验证码的手机号
    private int clickCount = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerSmsReceiver();
    }

    protected void findViewById() {
        setContentView(R.layout.login_main);
        super.findViewById();
        getAppTitle().setCommonTitle("登录");
        mMobileEdit = (EditText) findViewById(R.id.login_mobile_edit);
        mMobileEdit.addTextChangedListener(new droid.frame.view.TextWatcherExt(1) {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 可以修改手机号, 但是必须等到60s以后才可以重新发送
                if (s.length() == 13 && recLen == 30) {
                    mGetCodeTextView.setEnabled(true);
                    mGetCodeTextView.setTextColor(getResources().getColor(R.color.app_font_green));
                    if (mCheckBox.isChecked() && mCodeEdit.getText().length() >= 4) {
                        mSubmitTV.setEnabled(true);
                    } else {
                        mSubmitTV.setEnabled(false);
                    }
                } else {
                    mSubmitTV.setEnabled(false);
                    mGetCodeTextView.setEnabled(false);
                    mGetCodeTextView.setTextColor(Color.parseColor("#6F8FAF"));
                }
            }
        });
        mCodeEdit = (EditText) findViewById(R.id.login_code_edit);
        mCodeEdit.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() >= 4) {
                    if (mCheckBox.isChecked() && mMobileEdit.getText().length() == 13) {
                        mSubmitTV.setEnabled(true);
                    } else {
                        mSubmitTV.setEnabled(false);
                    }
                } else {
                    mSubmitTV.setEnabled(false);
                }
                // 输入完寄件码，自动验证
                if (s.length() == 4) {
                    loginVerify();
                }
            }
        });
        mGetCodeTextView = (TextView) findViewById(R.id.login_get_code);
        mSubmitTV = (TextView) findViewById(R.id.submit_TV);
        mCheckBox = (CheckBox) findViewById(R.id.login_read_checkbox);
        mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {
                    mSubmitTV.setEnabled(false);
                } else {
                    if (mCodeEdit.getText().length() >= 4 && mMobileEdit.getText().length() == 13) {
                        mSubmitTV.setEnabled(true);
                    }
                }
            }
        });
        findViewById(R.id.login_read_tv).setOnClickListener(this);
        mGetCodeTextView.setOnClickListener(this);
        mSubmitTV.setOnClickListener(this);
        mSubmitTV.setEnabled(false);
        mGetCodeTextView.setEnabled(false);
        mGetCodeTextView.setTextColor(Color.parseColor("#6F8FAF"));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //获取验证码
            case R.id.login_get_code:
                if (mMobileEdit.getText().length() == 13) {
                    loginPhone = mMobileEdit.getText().toString().replace(" ", "");
                    showLoadingDialog(null);
                    if (clickCount > 2) {
                        AppHttp.getInstance().loginSMSVerifyCode(loginPhone, 2, "1");
                    } else {
                        AppHttp.getInstance().loginSMSVerifyCode(loginPhone, 2, "");
                    }
                } else {
                    showToast("手机号输入有误");
                }
                break;
            //登录按钮
            case R.id.submit_TV:
                loginVerify();
                break;
            //阅读协议
            case R.id.login_read_tv:
                Intent i = new Intent(getContext(), WebViewActivity.class);
                i.putExtra("title", "用户使用条款");
                startActivity(i);
                break;
            default:
                break;
        }
    }

    /**
     * 登录验证
     */
    private void loginVerify() {
        String phone = mMobileEdit.getText().toString().replace(" ", "");
        if (Str.isEmpty(phone) || Str.isEmpty(mCodeEdit.getText().toString())) {
            showToast("请输入手机号，获取验证码");
            return;
        }
        if (mCheckBox.isChecked() == false) {
            showToast("请阅读并同意软件许可服务协议");
            return;
        }
        showLoadingDialog(null);
        String code = mCodeEdit.getText().toString();
        AppHttp.getInstance().confirmLoginVerifyCode(phone, code);
    }

    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 发送验证码
            case MsgID.send_verifyNum:
                cancelLoadingDialog();
                ReqResult<?> result = JSON.parser(msg.obj);
                if (checkLoginStatus(result)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            countDownStart();
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            // 确认验证码,并登录
            case MsgID.confirmVerifyNum:
                cancelLoadingDialog();
                ReqResult<UserBean> result1 = JSON.parser(msg.obj, UserBean.class);
                if (checkLoginStatus(result1)) {
                    UserBean user = result1.getResult();
                    if (user != null) {
                        if (isEmpty(user.getPhone())) {
                            user.setPhone(mMobileEdit.getText().toString().replace(" ", ""));
                        }
                        AppCache.setUser(user);
                        Intent intent = new Intent();
                        intent.putExtra("isOpenStation", false);
                        intent.setClass(LoginChooseActivity.this, MainActivity.class);
                        startActivity(intent);
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        showToast("服务器异常");
                    }
                } else if (result1.getStatus() == 3002 || result1.getStatus() == 3003 || result1.getStatus() == 3004
                        || result1.getStatus() == 3005 || result1.getStatus() == 3007) {
                    //3002 驿站未注册 3003 驿站正在审核 3004 审核失败
                    // 3005 驿站被冻结，不能继续使用 3007 驿站已经支付，未填写资料
                    UserBean user = result1.getResult();
                    if (isEmpty(user.getPhone())) {
                        user.setPhone(mMobileEdit.getText().toString().replace(" ", ""));
                    }
                    AppCache.setUser(user);
                    if (result1.getStatus() == 3002) {
                        Intent intent = new Intent(getContext(), MainActivity.class);
                        intent.putExtra("isOpenStation", true);
                        startActivity(intent);
                    } else {
                        startActivity(MainActivity.class);
                    }
                    setResult(RESULT_OK);
                    finish();
                } else {
                    showToast(result1.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private int recLen = 30;
    private boolean isStart;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (recLen == 1) {
                isStart = false;
                recLen = 30;
                mGetCodeTextView.setEnabled(true);
                mGetCodeTextView.setTextColor(getResources().getColor(R.color.app_font_green));
                mGetCodeTextView.getPaint().setFlags(0);
                mGetCodeTextView.setText("重新获取");
            }
            if (recLen == 29) {
                clickCount++;
                showToast("短信验证码已发送");
            }
            if (isStart) {
                recLen--;
                mGetCodeTextView.setEnabled(false);
                mGetCodeTextView.setTextColor(Color.parseColor("#6F8FAF"));
                mGetCodeTextView.getPaint().setFlags(0);
                mGetCodeTextView.setText(recLen + "秒后重新发送");
                getHandler().postDelayed(this, 1000);
            }
        }
    };

    private void countDownStart() {
        getHandler().postDelayed(runnable, 1000);
        isStart = true;
        mGetCodeTextView.setEnabled(false);
        mCodeEdit.requestFocus();
        InputMethodManager imm = (InputMethodManager) mCodeEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    public Handler smsHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                mCodeEdit.setText(msg.obj.toString());
            }
        }
    };

    private void registerSmsReceiver() {
        smsFilter = new IntentFilter();
        smsFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        smsFilter.setPriority(Integer.MAX_VALUE);
        smsReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Object[] objs = (Object[]) intent.getExtras().get("pdus");
                for (Object obj : objs) {
                    byte[] pdu = (byte[]) obj;
                    SmsMessage sms = SmsMessage.createFromPdu(pdu);
                    String message = sms.getMessageBody();
                    String from = sms.getOriginatingAddress();
                    if (!TextUtils.isEmpty(from)) {
                        String code = patternCode(message);
                        if (!TextUtils.isEmpty(code)) {
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = code;
                            smsHandler.sendMessage(msg);
                        }
                    }
                }
            }
        };
        registerReceiver(smsReceiver, smsFilter);
    }

    /**
     * @param @param  patternContent
     * @param @return
     * @return String
     * @throws
     * @Title: 匹配短信中间的6个数字（验证码等）
     * @Description: TODO()
     */
    private String patternCode(String patternContent) {
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }
        Pattern p = Pattern.compile("(?<!\\d)\\d{4}(?!\\d)");
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (smsReceiver != null) {
            unregisterReceiver(smsReceiver);
        }
        if (runnable != null) {
            getHandler().removeCallbacks(runnable);
        }
    }
}
